﻿@page "/stockin-list"
@using Microsoft.EntityFrameworkCore
@using Wms.Core.Entities
@using Wms.Core.Extensions
@inject Wms.Data.WarehouseDbContext Db
@inject NavigationManager Navigation

<div class="container-fluid py-4">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="text-primary">
            <span class="oi oi-data-transfer-down me-2"></span> 入库单列表
        </h4>
        <button class="btn btn-primary btn-lg px-4" @onclick="AddNew">
            <span class="oi oi-plus me-1"></span> 新增入库单
        </button>
    </div>

    <!-- 列表表格 -->
    <div class="card shadow-sm">
        <div class="card-body p-0">
            @if (stockInOrders == null || !stockInOrders.Any())
            {
                <div class="text-center py-5">
                    @if (stockInOrders == null)
                    {
                        <div class="spinner-border text-primary" role="status"></div>
                        <p class="mt-3 text-muted">加载中...</p>
                    }
                    else
                    {
                        <img src="https://cdn.jsdelivr.net/gh/twbs/icons/icons/file-earmark-text.svg" alt="空数据" width="48" class="mb-3 opacity-50" />
                        <p class="text-muted">暂无入库单记录，点击上方按钮新增。</p>
                    }
                </div>
            }
            else
            {
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th scope="col">单号</th>
                                <th scope="col">日期</th>
                                <th scope="col" class="text-center">类型</th>
                                <th scope="col" class="text-center">明细项数</th>
                                <th scope="col" class="text-center">总数量</th>
                                <th scope="col" class="text-center" style="width: 150px;">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach (var order in stockInOrders)
                            {
                                <tr>
                                    <td>
                                        <strong>@order.OrderNo</strong>
                                    </td>
                                    <td>@order.Date.ToString("yyyy-MM-dd HH:mm")</td>
                                    <td class="text-center">
                                        <span class="badge bg-secondary">@stockInTypeMap[order.Type]</span>
                                    </td>
                                    <td class="text-center text-primary">
                                        @order.Details.Count
                                    </td>
                                    <td class="text-center">
                                        <span class="badge bg-success">@order.TotalQuantity()</span>
                                    </td>
                                    <td class="text-center">
                                        <!-- 查看 -->
                                        <button class="btn btn-sm btn-outline-info me-1"
                                                @onclick="() => ViewDetail(order.Id)"
                                                title="查看明细">
                                            <span class="oi oi-eye"></span>
                                        </button>

                                        <!-- 编辑 -->
                                        <button class="btn btn-sm btn-outline-warning me-1"
                                                @onclick="() => EditOrder(order.Id)"
                                                title="编辑">
                                            <span class="oi oi-pencil"></span>
                                        </button>

                                        <!-- 删除 -->
                                        <button class="btn btn-sm btn-outline-danger me-1"
                                                @onclick="() => ConfirmDelete(order.Id, order.OrderNo)"
                                                title="删除">
                                            <span class="oi oi-trash"></span>
                                        </button>
                                    </td>
                                </tr>
                            }
                        </tbody>
                    </table>
                </div>
            }
        </div>
    </div>

    <!-- 返回顶部按钮（可选） -->
    <div class="mt-3 text-end">
        <button class="btn btn-sm btn-outline-secondary" @onclick="ScrollToTop">
            <span class="oi oi-arrow-thick-top"></span> 顶部
        </button>
    </div>
</div>
@inject IJSRuntime JSRuntime
<!-- 删除确认模态框 -->
@if (showDeleteModal)
{
    <div class="modal fade show d-block" style="display: block; background: rgba(0,0,0,0.5);" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title text-danger">
                        <span class="oi oi-warning me-2"></span> 确认删除
                    </h5>
                    <button type="button" class="btn-close" @onclick="() => showDeleteModal = false"></button>
                </div>
                <div class="modal-body">
                    <p>确定要删除入库单 <strong>@deletingOrderNo</strong> 吗？</p>
                    <p class="text-danger small">此操作将删除所有相关明细，且不可撤销！</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" @onclick="() => showDeleteModal = false">取消</button>
                    <button type="button" class="btn btn-danger" @onclick="ExecuteDelete">确认删除</button>
                </div>
            </div>
        </div>
    </div>
}
@code {
    private readonly Dictionary<StockInType, string> stockInTypeMap = new()
    {
        { (StockInType)0, "未知类型" },
        { StockInType.Purchase, "采购入库" },
        { StockInType.Production, "生产入库" },
        { StockInType.Return, "退货入库" }
    };
    private List<StockInOrder> stockInOrders;

    protected override void OnInitialized()
    {
        stockInOrders = Db.StockInOrders
            .Include(o => o.Details)
            .OrderByDescending(o => o.Date)
            .ToList();
    }

    private void AddNew()
    {
        Navigation.NavigateTo("/stockin");
    }

    private void ViewDetail(int id)
    {
        Navigation.NavigateTo($"/stockin-detail/{id}");
    }

    private void EditOrder(int id)
    {
        Navigation.NavigateTo($"/stockin/{id}");
    }

    private bool showDeleteModal = false;
    private int deletingOrderId;
    private string deletingOrderNo = string.Empty;

    private void ConfirmDelete(int id, string orderNo)
    {
        deletingOrderId = id;
        deletingOrderNo = orderNo;
        showDeleteModal = true;
    }

    private async Task ExecuteDelete()
    {
        var order = Db.StockInOrders
            .Include(o => o.Details)
            .FirstOrDefault(o => o.Id == deletingOrderId);

        if (order != null)
        {
            try
            {
                // 删除明细（外键约束需先删明细）
                Db.StockInDetails.RemoveRange(order.Details);
                Db.StockInOrders.Remove(order);
                await Db.SaveChangesAsync();

                // 重新加载列表
                stockInOrders = Db.StockInOrders
                    .Include(o => o.Details)
                    .OrderByDescending(o => o.Date)
                    .ToList();

                await JSRuntime.InvokeVoidAsync("alert", $"入库单 {deletingOrderNo} 已删除。");
            }
            catch (Exception ex)
            {
                await JSRuntime.InvokeVoidAsync("alert", $"删除失败：{ex.Message}");
            }
        }

        showDeleteModal = false;
    }
    private async Task ScrollToTop()
    {
        await JSRuntime.InvokeVoidAsync("scrollTo", 0, 0);
    }
}